import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqLogout } from '@/services/user'
import type {
  loginFormData,
  loginResponseeData,
  userInfoResponseeData,
} from '@/services/user/type'
import type { UserState } from './types/type.ts'
import { reactive } from 'vue'
import { SET_TOKEN, GET_TOKEM, REMOVE_TOKEN } from '@/utlis/token.ts'
import { constantRoute } from '@/router/routes.ts'
const useUserStore = defineStore('user', () => {
  //登录方法
  const userInfo = reactive<UserState>({
    token: GET_TOKEM(), //用户唯一标识
    menuRoutes: constantRoute,
    username: '',
    avatar: '',
  })
  // 用户登录
  const userLogin = async (data: loginFormData) => {
    const result: loginResponseeData = await reqLogin(data)
    if (result.code == 200) {
      userInfo.token = result.data as string
      SET_TOKEN(result.data as string)
      return 'ok'
    } else {
      return Promise.reject(new Error(result.data))
    }
  }
  //获取用户信息
  const UserInfoDetail = async () => {
    const res: userInfoResponseeData = await reqUserInfo()
    // 如果获取用户信息成功就存储
    if (res.code == 200) {
      userInfo.username = res.data.name
      userInfo.avatar = res.data.avatar
      return 'ok'
    } else {
      return Promise.reject(new Error(res.message))
    }
  }

  // 退出登录
  const userLogout = async () => {
    const res: any = await reqLogout()
    if (res.code == 200) {
      userInfo.token = ''
      userInfo.username = ''
      userInfo.avatar = ''
      REMOVE_TOKEN()
      return 'ok'
    } else {
      return Promise.reject(new Error(res.message))
    }
  }
  return { userLogin, userInfo, UserInfoDetail, userLogout }
})

export default useUserStore
